package com.example.demo.mapper;

import com.example.demo.entity.Message;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface MessageMapper {

    @Insert("INSERT INTO message (sender_id, receiver_id, content, is_read, created_at) " +
            "VALUES (#{senderId}, #{receiverId}, #{content}, #{isRead}, #{createdAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertMessage(Message message);

    @Select("SELECT m.*, u.avatar AS sender_avatar " +
            "FROM message m " +
            "JOIN user u ON m.sender_id = u.id " +
            "WHERE m.receiver_id = #{receiverId} " +
            "ORDER BY m.created_at DESC")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "senderId", column = "sender_id"),
            @Result(property = "receiverId", column = "receiver_id"),
            @Result(property = "content", column = "content"),
            @Result(property = "isRead", column = "is_read"),
            @Result(property = "createdAt", column = "created_at"),
            @Result(property = "senderAvatar", column = "sender_avatar") // 映射发送者头像
    })
    List<Message> findMessagesByReceiverId(Long receiverId);
}
